﻿using System;
using System.Collections.Generic;
using System.Net;

public class UserServerCollection
{
    AtomLock m_Lock = new AtomLock();
    /// <summary>
    /// 已识别的用户集合组
    /// </summary>
    Dictionary<long, UserServer> m_Users = new Dictionary<long, UserServer>();
    public Dictionary<long, UserServer> users => m_Users;

    /// 用户是否存在 
    public bool ExistUser(long id)
    {
        if (id == 0) return false;

        bool ret = false;

        m_Lock.DoAction(() => ret = m_Users.ContainsKey(id));

        return ret;
    }

    /// 查找用户
    public UserServer FindUser(long id)
    {
        if (id == 0) return null;
        
        UserServer netUser = null;

        m_Lock.DoAction(() => m_Users.TryGetValue(id, out netUser));

        return netUser;
    }

    /// 添加用户
    public void AddUser(UserServer netUser)
    {
        if (netUser.data.id == 0)
        {
            GameDebug.LogError("错误的用户id: " + netUser.data.id);
        }

        // 添加用户
        m_Lock.DoAction(() => m_Users[netUser.data.id] = netUser);
    }

    //public void RemoveUser(UserServer netUser)
    //{
    //    m_Lock.DoAction(() => m_Users.Remove(netUser.data.id));
    //}

    public void RemoveUser(long  userId,IPEndPoint ip)
    {
        GameDebug.Log($"移除用户：{userId}  ip:{ip}");
        m_Lock.DoAction(() => m_Users.Remove(userId));
    }

    public void ClearAllUsers()
    {
        m_Lock.DoAction(() => m_Users.Clear());
    }

    public void ForeachAction(Action<UserServer> action)
    {
        m_Lock.DoAction(() => 
        {
            m_Users.Values.ForEach(e=> 
            {
                action?.Invoke(e);
            }
            );
        });
    }

    public string  Log()
    {
        string str = "";
        m_Lock.DoAction(() => str = $"{m_Users.GetDictStr()}");
        return str;
    }
}

